using System.Collections.Generic;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;

namespace LeastPrivilege.CustomBasicAuthentication.Management
{
    // the module service' job is to read/write to the server config
    class CustomBasicAuthenticationModuleService : ConfigurationAuthenticationModuleService
    {
        private CustomBasicAuthenticationSection _config;

        private CustomBasicAuthenticationSection Configuration
        {
            get
            {
                if (_config == null)
                {
                    ManagementConfiguration configuration = base.ManagementUnit.Configuration;

                    _config = (CustomBasicAuthenticationSection)configuration.GetSection(
                          CustomBasicAuthenticationSection.SectionName,
                          typeof(CustomBasicAuthenticationSection));
                }

                return _config;
            }
        }

        protected override string EnabledPropertyName
        {
            get { return "enabled"; }
        }

        protected override string SectionName
        {
            get { return CustomBasicAuthenticationSection.SectionName; }
        }

        [ModuleServiceMethod(PassThrough = true)]
        public PropertyBag GetConfiguration()
        {
            PropertyBag bag = new PropertyBag();
            bag.Add(1, Configuration.Realm);
            bag.Add(2, Configuration.ProviderName);
            bag.Add(3, Configuration.CachingEnabled);
            bag.Add(4, Configuration.CachingDuration);
            bag.Add(5, Configuration.RequireSSL);


            return bag;
        }

        [ModuleServiceMethod(PassThrough = true)]
        public PropertyBag GetEnabled()
        {
            PropertyBag bag = new PropertyBag();
            bag.Add(1, Configuration.Enabled);
            bag.Add(2, Configuration.IsLocked);

            return bag;
        }

        [ModuleServiceMethod(PassThrough = true)]
        public void SetConfiguration(PropertyBag bag)
        {
            Configuration.Realm = (string)bag[1];
            Configuration.ProviderName = (string)bag[2];
            Configuration.CachingEnabled = bool.Parse(bag[3].ToString());
            Configuration.CachingDuration = int.Parse(bag[4].ToString());
            Configuration.RequireSSL = bool.Parse(bag[5].ToString());

            base.ManagementUnit.Update();
        }

        [ModuleServiceMethod(PassThrough = true)]
        public void SetEnabled(bool enabled)
        {
            Configuration.Enabled = enabled;
            
            base.ManagementUnit.Update();
        }
    }
}
